<?php

namespace app\admin\controller\jeek;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Session;
/**
 * 产品
 *
 * @icon fa fa-circle-o
 */
class Product extends Backend
{

    /**
     * Product模型对象
     * @var \app\common\model\jeek\Product
     */
    protected $model = null;

    protected $dataLimit = 'auth'; //这个属性在基类已经定义，默认为false，表示不启用，$dataLimit可使用auth和personal两个值
    protected $dataLimitField = 'admin_id';
    // protected $dataLimitFieldAutoFill = true;
    /**
     * 初始化方法
     * 该方法主要用于初始化控制器，包括加载模型、处理分类数据以及为视图赋值
     * 它为当前控制器的视图准备了必要的数据，如状态列表、推荐列表、审核类型列表和热门列表
     * 同时，它还处理了分类数据的树形结构转换，并将其分配给视图
     */
    public function _initialize()
    {
        // 调用父类的初始化方法，确保基础环境被正确设置
        parent::_initialize();
    
        // 实例化产品模型，用于后续的数据获取和处理
        $this->model = new \app\common\model\jeek\Product;
    
        // 为视图分配状态列表、推荐列表、审核类型列表和热门列表
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("recommendList", $this->model->getRecommendList());
        $this->view->assign("shTypeList", $this->model->getShTypeList());
        $this->view->assign("hotList", $this->model->getHotList());
    
        // 实例化分类模型，用于获取分类数据
        $categoryModel= new \app\common\model\jeek\Category;
    
        // 使用Tree类处理分类数据，生成树形结构
        $tree = Tree::instance();
        $tree->init(collection($categoryModel->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
    
        // 构建分类数据数组，包括所有分类和一个"无分类"选项
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
    
        // 为视图分配处理后的分类数据
        $this->view->assign("parentList", $categorydata);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 复制产品
     */
    public function copy()
    {
        // 获取要复制的产品ID
        $id = $this->request->param('ids');
        if (!$id) {
            $this->error(__('参数错误'));
        }

        // 查找对应的产品数据
        $product = $this->model->find($id);
        if (!$product) {
            $this->error(__('没有找到结果'));
        }

        // 将原产品数据转换为数组并移除原ID
        $productData = $product->toArray();
        // ["status_text"] => string(9) "待发布"
        // ["recommend_text"] => string(9) "不推荐"
        // ["sh_type_text"] => string(9) "Sh_type 0"
        // ["hot_text"] => string(6) "正常"
        unset($productData['id']);
       
        unset($productData['status_text']);
        unset($productData['recommend_text']);
        unset($productData['sh_type_text']);
        unset($productData['hot_text']);
        unset($productData['is_hidden']);
       
        // 在title字段后添加“复制”
        $productData['title'] .= '复制';

        // 设置新数据的admin_id为当前登录的管理员ID
        $productData['admin_id'] = $this->auth->id;

        // dump($productData);die();

        // 使用模型的create方法插入新的产品数据
        $newProductId = Db::name('jeek_product')->insertGetId($productData);
        if ($newProductId) {
            // 更新新插入记录的weigh字段为新插入记录的ID
            // Db::name('jeek_product')->where('id', $newProductId)->update(['weigh' => $newProductId]);
        // 复制规格数据
        $specifications = Db::name('jeek_products_price')->where('product_id', $id)->select();
        foreach ($specifications as $specification) {
            // $specData = $specification->toArray();
            $specData = $specification;
            unset($specData['id']);
            $specData['product_id'] = $newProductId;
            Db::name('jeek_products_price')->insert($specData);
        }



            $this->success(__('复制成功'));
        } else {
            $this->error(__('复制失败'));
        }
    }

    /**
     * 批量隐藏产品
     */
    // public function hide()
    // {
    //     // 获取要隐藏的产品ID
    //     $ids = $this->request->param('ids');
    //     if (!$ids) {
    //         $this->error(__('参数错误'));
    //     }

    //     // 将ID字符串转换为数组
    //     $ids = explode(',', $ids);

    //     // 获取当前登录管理员的隐藏产品ID
    //     $hiddenIds = $this->auth->hidden_products ?: [];

    //     // 计算需要新增和移除的隐藏产品ID
    //     $newHiddenIds = array_diff($ids, $hiddenIds);
    //     $removeHiddenIds = array_intersect($ids, $hiddenIds);

    //     // 更新隐藏产品ID
    //     $newHiddenIds = array_merge(array_diff($hiddenIds, $removeHiddenIds), $newHiddenIds);

    //     // 保存更新后的隐藏产品ID到管理员信息中
    //     Db::name('jeek_merchant')->where('id', $this->auth->id)->update(['hidden_products' => implode(',', $newHiddenIds)]);

    //     $this->success(__('隐藏成功'));
    // }
    
     /**
      * 切换隐藏状态
      */
      public function toggle_hide()
      {
          $productId = $this->request->post('id');
          $adminId = $this->auth->id;
      
          // 验证是否为平台分类
          $product = $this->model->where('id', $productId)
              ->where('admin_id', 'in',[1,$adminId])
              ->find();
          if (!$product) {
              $this->error(__('Invalid parameters'));
          }
      
          // 判断当前隐藏状态
          $exists = Db::name('jeek_products_hide')
              ->where('admin_id', $adminId)
              ->where('product_id', $productId)
              ->count();
      
          if ($exists) {
              // 取消隐藏
              Db::name('jeek_products_hide')
                  ->where('admin_id', $adminId)
                  ->where('product_id', $productId)
                  ->delete();
          } else {
              // 添加隐藏
              Db::name('jeek_products_hide')->insert([
                  'admin_id' => $adminId,
                  'product_id' => $productId
              ]);
          }
      
          $this->success();
      }
      
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
           $this->dataLimit=false;//不启用数据权限
    

      
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
                  // 获取当前登录管理员信息
        $admin = Session::get("admin");
        $auth_group_access = Db::name('auth_group_access')->where('uid', $admin['id'])->find();

        $where = function ($query) use ($admin) {
            $query->where('product.admin_id', 'in', [1, $admin['id']]);
        };
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();



        
// 修改查询条件，包含admin_id为1的产品数据
// $where = function ($query) use ($admin) {
//     $query->where('product.admin_id', 'in', [1, $admin['id']]);
// };

        // 解析前端提交的查询条件
        $op = $this->request->request('filter');
        // dump($op);die();
        if ($op) {
            $op = json_decode($op, true);
            if (isset($op['category.name'])) {
                $categoryName = $op['category.name'];
                // 获取分类ID
                $category = Db::name('jeek_category')->where('name', $categoryName)->find();
                if ($category) {
                    $categoryId = $category['id'];
                } else {
                    $categoryId = null;
                }
            }else {
                $categoryId = null;
            }
        } else {
            $categoryId = null;
        }

        // 修改查询条件，包含admin_id为1的产品数据，并且包含分类条件
        $where = function ($query) use ($admin, $categoryId, $where) {
             // 合并 buildparams 生成的基本查询条件
             if ($where instanceof \Closure) {
                $where($query);
            }

            // 添加 admin_id 条件
            $query->where('product.admin_id', 'in', [1, $admin['id']]);

            // 添加分类条件
            if ($categoryId !== null) {
                $query->where('product.category_id', $categoryId);
            }
        };
        
        
       

        // 获取当前分销商已隐藏的分类ID
        $hiddenIds = Db::name('jeek_products_hide')
            ->where('admin_id', $admin['id'])
            ->column('product_id');


        $list = $this->model
            ->with(['category', 'admin'])
            ->where($where)
           
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as $row) {
            $row->visible(['id', 'title', 'image', 'status', 'admin_id', 'weigh', 'price', 'description']);
            $row->visible(['category']);
            $row->getRelation('category')->visible(['name']);
            $row->visible(['admin']);
        }
// dump($where);dump($list);die();
        // 重构分类过滤逻辑
        $filteredList = [];
        foreach ($list->items() as $v) {
            // 平台数据且未被隐藏，或分销商自己创建的数据
            if ($v['admin_id'] == 1  || $v['admin_id'] == $admin['id']) {
                // 添加隐藏状态标识
                $v['is_hidden'] = in_array($v['id'], $hiddenIds) ? 1 : 0;
                $filteredList[] = $v;
            }
        }
            $result = array("total" => $list->total(), "rows" => $filteredList);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function searchlist()
    {

        $guanli= Session::get("admin");//当前登录者
        $auth_group_access=DB::name('auth_group_access')->where(array('uid'=>$guanli['id']))->find();//等级
        $this->assignconfig("admin", $auth_group_access);
        $this->relationSearch = true;
        if($auth_group_access['group_id']==2){
            $admin=DB::name('admin')->where(array('id'=>$guanli['id']))->find();//
          
            $a[]=1;
            array_unshift($a,$admin['id']);

            $nav=Db::name('jeek_category')->where('admin_id','in',$a)->order('weigh desc')->select();


        }else{
            $map['type']='product';
            $map['admin_id']=$guanli['id'];
            $nav=Db::name('jeek_category')->where($map)->order('weigh desc')->select();
// dump($nav);die();

        }


        $categoryList = collection( $nav)->toArray();
        Tree::instance()->init($categoryList);
        $searchlist = [];
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        foreach ($result as $k => $v) {

            if (strpos($v['name'], '├') !== false) {
                $values=strstr($v['name'],"├");
                $length = strlen("├");
                $values=substr($values, $length);
            }elseif (strpos($v['name'], '└') !== false) {
                $values=strstr($v['name'],"└");
                $length = strlen("└");
                $values=substr($values, $length);
            } else {
                $values=$v['name'];
            }

            $searchlist[] = ['id' => $values, 'name' => $v['name'], 'pid' => $v['pid']];
        }
        return json($searchlist);
    }

    /**
     * 获取分类树形结构
     */
    public function getCategoryTree()
    {
        // 实例化分类模型，用于获取分类数据
        $categoryModel = new \app\common\model\jeek\Category;

        // 使用Tree类处理分类数据，生成树形结构
        $tree = Tree::instance();
        $tree->init(collection($categoryModel->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $categoryTree = $tree->getTreeList($tree->getTreeArray(0), 'name');

        return json(['rows' => $categoryTree]);
    }

}
